var context = {
	//need move to storage, as it will consume a lot of memory
	thumbnails : {}
};

(function(){

	var capturePreviewThumbnail = function(tabId, windowId){
		try{
			chrome.tabs.captureVisibleTab(windowId, {format:"png"}, function(dataUrl){
				context.thumbnails[tabId] = dataUrl;
			});
		}catch(e){
			console.error('cannot handle capture request', e);
		}
	};

	chrome.tabs.onActivated.addListener(function(activeInfo){
		setTimeout(1000, capturePreviewThumbnail(activeInfo.tabId, activeInfo.windowId));
	});
/*
	chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
		if(tab.status == "complete" && tab.highlighted && tab.active){
			capturePreviewThumbnail(tabId, tab.windowId);
		}
	});
*/
	chrome.tabs.onRemoved.addListener(function(tabId, removeInfo){
		delete context.thumbnails[tabId];
	});
	

	chrome.extension.onRequest.addListener(function(request, sender, sendResponse){
		if (request.fun == "queryThumbnail"){
			var tabId = request.data.tabId;
			sendResponse(context.thumbnails[tabId]);
		}
	});
}).call(this);